import React, { useEffect, useState } from "react";
import ProTypes from "prop-types";

import useInputFocus from "../hooks/useInputFocus";
import useKeyPress from "../hooks/useKeyPress";
import useContextMenu from "../hooks/useContextMenu";
import { getParentNode } from "../utils/helper";

const FileList = (props) => {
    // 解构props
    const { files, onFileClick, onSaveEdit, onFileDelete } = props;

    const [editStatus, setEditStatus] = useState("");
    const [value, setValue] = useState("");
    // 按下enter
    const enterPressed = useKeyPress(13);
    // 按下esc
    const escPressed = useKeyPress(27);

    // 关闭当前编辑的文件
    const closeSearch = (editItem) => {
        console.log("关闭input");
        // 取消input显示
        setEditStatus("");
        // 清空已输入的input value
        setValue("");

        // 如果在编辑一个新文件,按了esc键时,就把当前编辑的文件从列表删除
        if (editItem && editItem.isNew) {
            onFileDelete(editItem.id);
        }
    };

    // 右键菜单
    const clickedItem = useContextMenu(
        [
            {
                label: "打开",
                click: () => {
                    const parentElement = getParentNode(clickedItem.current, "file-item");
                    const { id } = parentElement.dataset;
                    if (parentElement) {
                        onFileClick(id);
                    }
                },
            },
            {
                label: "重命名",
                click: () => {
                    const parentElement = getParentNode(clickedItem.current, "file-item");
                    const { id, title } = parentElement.dataset;
                    if (parentElement) {
                        setEditStatus(id);
                        setValue(title);
                    }
                },
            },
            {
                label: "删除",
                click: () => {
                    const parentElement = getParentNode(clickedItem.current, "file-item");
                    const { id } = parentElement.dataset;
                    if (parentElement) {
                        onFileDelete(id);
                    }
                },
            },
        ],
        ".file-list",
    );

    // 监听新创建的文件
    useEffect(() => {
        const newFile = files.find((file) => file.isNew);
        if (newFile) {
            setEditStatus(newFile.id);
            setValue(newFile.title);
        }
    }, [files]);

    // 监听键盘事件
    useEffect(() => {
        const editItem = files.find((file) => file.id === editStatus);
        if (enterPressed && editStatus && value.trim() !== "") {
            // 把文件id和修改的内容传出去
            onSaveEdit(editItem.id, value, editItem.isNew);
            // 这里没调用关闭方法，导致报错，找了很久。草草草草！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！
            closeSearch();
        }
        if (escPressed && editStatus) {
            closeSearch(editItem);
        }
    }, [enterPressed, escPressed]);
    // input聚焦
    const inputRef = useInputFocus(editStatus);

    return (
        <ul className="list-group list-group-flush file-list">
            {files.map((file) => {
                return (
                    <li
                        key={file.id}
                        className="list-group-item bg-light d-flex align-items-center file-item justify-content-between"
                        data-id={file.id}
                        data-title={file.title}
                    >
                        {file.id !== editStatus && !file.isNew && (
                            <>
                                <div className="left" onClick={() => onFileClick(file.id)}>
                                    <i className="bi bi-markdown me-1"></i>
                                    <span className={"c-pointer"}>{file.title}</span>
                                </div>
                                <div className="right">
                                    <button
                                        type="button"
                                        className="icon-button"
                                        onClick={() => {
                                            setEditStatus(file.id);
                                            setValue(file.title);
                                        }}
                                    >
                                        <i className="bi bi-pencil-square"></i>
                                    </button>
                                    <button type="button" className="icon-button" onClick={() => onFileDelete(file.id)}>
                                        <i className="bi bi-trash"></i>
                                    </button>
                                </div>
                            </>
                        )}
                        {(file.id === editStatus || file.isNew) && (
                            <>
                                {/* 这里的 col-8 必须写在外层div上，如果写在input上，就会和form-control样式冲突 */}
                                <div className="">
                                    <input
                                        ref={inputRef}
                                        className="form-control search-height"
                                        value={value}
                                        placeholder="请输入文件名称"
                                        onChange={(e) => {
                                            setValue(e.target.value);
                                        }}
                                    />
                                </div>
                                <button type="button" className="icon-button" onClick={() => closeSearch(file)}>
                                    <i className="bi bi-x-lg"></i>
                                </button>
                            </>
                        )}
                    </li>
                );
            })}
        </ul>
    );
};

FileList.propTypes = {
    files: ProTypes.array,
    onFileClick: ProTypes.func,
    onSaveEdit: ProTypes.func,
    onFileDelete: ProTypes.func,
};

export default FileList;
